package cn.ithers.blog.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.ithers.blog.dao.SettingDao;
import cn.ithers.blog.pojo.Setting;
import cn.ithers.blog.response.ResponseResult;
import cn.ithers.blog.service.IWebSiteInfoService;
import cn.ithers.blog.utils.Constants;
import cn.ithers.blog.utils.IdWorker;
import cn.ithers.blog.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Struct;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhanghuan
 * @date: 2020/10/4 20:24
 * @description:
 */
@Slf4j
@Service
public class WebSiteInfoServiceImpl extends BaseService implements IWebSiteInfoService {

    @Autowired
    private SettingDao settingDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取网站标题
     *
     * @return
     */
    @Override
    public ResponseResult getWebSiteTitle() {
        Setting title = settingDao.findOneByKey(Constants.Settings.WEB_SITE_TITLE);
        return ResponseResult.SUCCESS("获取网站标题成功").setData(title);
    }

    /**
     * 更新标题
     *
     * @param title
     * @return
     */
    @Override
    public ResponseResult putWebSiteTitle(String title) {
        if (StrUtil.isEmpty(title)) {
            return ResponseResult.FAILED("网站标题不可为空");
        }
        Setting titleFromDb = settingDao.findOneByKey(Constants.Settings.WEB_SITE_TITLE);
        if (titleFromDb == null) {
            titleFromDb = new Setting();
            titleFromDb.setId(idWorker.nextId() + "");
            titleFromDb.setCreateTime(new Date());
            titleFromDb.setKey(Constants.Settings.WEB_SITE_TITLE);
        }
        titleFromDb.setValue(title);
        titleFromDb.setUpdateTime(new Date());
        settingDao.save(titleFromDb);
        return ResponseResult.SUCCESS("网站标题更新成功");
    }

    /**
     * 获取网站信息
     *
     * @return
     */
    @Override
    public ResponseResult getSeoInfo() {
        Setting description = settingDao.findOneByKey(Constants.Settings.WEB_SITE_DESCRIPTION);
        Setting keyWords = settingDao.findOneByKey(Constants.Settings.WEB_SITE_KEYWORDS);
        Map<String, String> result = new HashMap<>();
        result.put(keyWords.getKey(), description.getValue());
        return ResponseResult.SUCCESS("获取seo信息成功").setData(result);
    }

    /**
     * 更新网站信息
     *
     * @param keywords
     * @param description
     * @return
     */
    @Override
    public ResponseResult putSeoInfo(String keywords, String description) {
        if (StrUtil.isEmpty(keywords)) {
            return ResponseResult.FAILED("关键字不可为空");

        }
        if (StrUtil.isEmpty(description)) {
            return ResponseResult.FAILED("描述不可以为空");
        }
        Setting descriptionFromDb = settingDao.findOneByKey(Constants.Settings.WEB_SITE_DESCRIPTION);

        if (descriptionFromDb == null) {
            descriptionFromDb = new Setting();
            descriptionFromDb.setId(idWorker.nextId() + "");
            descriptionFromDb.setCreateTime(new Date());
            descriptionFromDb.setKey(Constants.Settings.WEB_SITE_DESCRIPTION);
        }
        descriptionFromDb.setValue(description);
        descriptionFromDb.setUpdateTime(new Date());
        settingDao.save(descriptionFromDb);

        Setting keyWordsFromDb = settingDao.findOneByKey(Constants.Settings.WEB_SITE_KEYWORDS);

        if (keyWordsFromDb == null) {
            keyWordsFromDb = new Setting();
            keyWordsFromDb.setId(idWorker.nextId() + "");
            keyWordsFromDb.setCreateTime(new Date());
            keyWordsFromDb.setKey(Constants.Settings.WEB_SITE_KEYWORDS);
        }
        keyWordsFromDb.setValue(keywords);
        keyWordsFromDb.setUpdateTime(new Date());
        settingDao.save(keyWordsFromDb);
        return ResponseResult.SUCCESS("更新成功");
    }

    /**
     * 这个全网站的访问量，要做的细一些，还得分来源
     * 这里只统计浏览量，只统计文章的，提供一个浏览器的统计接口（页面级的）
     *
     * @return
     */
    @Override
    public ResponseResult getSiteViewCount() {
        Setting viewCount = settingDao.findOneByKey(Constants.Settings.WEB_SITE_VIEW_COUNT);
        if (viewCount == null) {
            viewCount = initViewItem();
            settingDao.save(viewCount);
        }
        //先从reids拿出来
        String viewCountStr = (String) redisUtils.get(Constants.Settings.WEB_SITE_VIEW_COUNT);
        if (StrUtil.isEmpty(viewCountStr)) {
            viewCountStr = viewCount.getValue();
            redisUtils.set(Constants.Settings.WEB_SITE_VIEW_COUNT, viewCountStr);
        } else {
            //把redis里的更新到数据库里
            viewCount.setValue(viewCountStr);
            settingDao.save(viewCount);
        }

        Map<String, Integer> result = new HashMap<>();
        result.put(viewCount.getKey(), Integer.valueOf(viewCount.getValue()));

        return ResponseResult.SUCCESS("获取网站浏览量成功").setData(result);
    }

    /**
     *实际开发中要考虑并发量
     * 2.过滤相同的ip
     * 3.防止攻击，比如太频繁的访问
     */
    @Override
    public void updateViewCount() {
        //reids更新时机
        Object viewCount = redisUtils.get(Constants.Settings.WEB_SITE_VIEW_COUNT);
        if (viewCount == null) {
            Setting setting = settingDao.findOneByKey(Constants.Settings.WEB_SITE_VIEW_COUNT);
            if (setting == null) {
                setting = initViewItem();
                settingDao.save(setting);
            }
            String viewCountStr = setting.getValue();
            redisUtils.set(Constants.Settings.WEB_SITE_VIEW_COUNT, viewCountStr);

        } else {
            //自增
            redisUtils.incr(Constants.Settings.WEB_SITE_VIEW_COUNT, 1);
        }
    }

    private Setting initViewItem() {
        Setting viewCount;
        viewCount = new Setting();
        viewCount.setId(idWorker.nextId() + "");
        viewCount.setKey(Constants.Settings.WEB_SITE_VIEW_COUNT);
        viewCount.setCreateTime(new Date());
        viewCount.setUpdateTime(new Date());
        viewCount.setValue("1");
        return viewCount;
    }
}
